package fun.tan90.device.source.core;

import fun.tan90.device.event.EventTopic;
import fun.tan90.device.event.BaseFactory;
import fun.tan90.device.event.model.DataHandleFailure;
import fun.tan90.device.event.model.DataHandleSuccess;
import fun.tan90.device.event.model.DeviceSourceData;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.noear.dami.Dami;
import org.noear.snack.ONode;

import java.util.concurrent.Future;

import static fun.tan90.device.event.threadpool.ThreadPool.SOURCE_FIXED_EXECUTOR;

@Slf4j
@Getter
public abstract class SourceFactory extends BaseFactory {

    @Override
    public String topicName() {
        return EventTopic.SOURCE_INFO_TOPIC;
    }

    @Override
    public ONode ruleNode() {
        return Dami.<String, ONode>bus().sendAndRequest(EventTopic.SOURCE_RULE_TOPIC, getPluginName());
    }

    public void afterPost(DeviceSourceData deviceSourceData) {
        Future<?> future = SOURCE_FIXED_EXECUTOR.submit(() -> {
            Dami.<DeviceSourceData, Void>bus().send(EventTopic.DEVICE_SOURCE_DATA_TOPIC, deviceSourceData);
        });
        try {
            future.get();
            Dami.<DataHandleSuccess, Void>bus().send(EventTopic.DATA_HANDLE_SUCCESS_TOPIC, DataHandleSuccess.builder()
                    .pluginName(getPluginName())
                    .deviceCode(deviceSourceData.getDeviceCode())
                    .deviceType(deviceSourceData.getDeviceType())
                    .dataSource(deviceSourceData.getDataSource())
                    .build());
        } catch (Exception e) {
            Dami.<DataHandleFailure, Void>bus().send(EventTopic.DATA_HANDLE_FAILURE_TOPIC, DataHandleFailure.builder()
                    .pluginName(getPluginName())
                    .deviceCode(deviceSourceData.getDeviceCode())
                    .deviceType(deviceSourceData.getDeviceType())
                    .dataSource(deviceSourceData.getDataSource())
                    .throwable(e)
                    .build());
        }
    }
}
